package ranab.server;

import java.io.*;
import java.net.*;

/**
 * This is a echo server
 */
public 
class DebugServer extends BaseServer {

    private InetAddress mAddress;
    private int mPort;


    public DebugServer(int port) {
        this(port, null);
    }
    
    public DebugServer(int port, InetAddress address) {
        mPort = port;
        mAddress = address;
    }
    
    
    /**
     * Get server bind address. Default is localhost.
     */
    public InetAddress getServerAddress() {
        return mAddress;
    }
    

	/**
	 * Get server port
	 */
	public int getServerPort() {
		return mPort;
	}


	/**
	 * Returns the server name
	 */
	public String getServerName() {
		return "Debug";
	}

	/**
	 * Serving request.
	 */
	public void serveRequest(Socket dataSoc) {        
        try {
            MessageEchoer echo = new MessageEchoer(dataSoc);
            echo.start();
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        finally {
            try {
                if(dataSoc != null) {
                    dataSoc.close();
                }
            }
            catch(Exception ex1) {
            }
        }
	}
    
    
    /**
     * Starting point
     */
    public static void main(String args[]) {
        
        // input argument check
        if(args.length != 1) {
            System.out.println("Usage: java ranab.server.DebugServer <port> [<address>]");
            System.exit(1);
        }
        
        try {
            int port = Integer.parseInt(args[0]);
            InetAddress addr = null;
            if(args.length > 1) {
                addr = InetAddress.getByName(args[1]);
            }
            
            DebugServer server = new DebugServer(port, addr);
            ServerEngine engine = new ServerEngine(server);
            engine.startServer();
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
